package com.giscloud.generator.core.intercepter;


import com.giscloud.commons.utils.FastJsonUtils;
import com.giscloud.commons.utils.NetUtils;
import com.giscloud.commons.utils.StringUtils;
import com.giscloud.generator.constant.RedisConstant;
import com.giscloud.generator.entity.vo.UserIdentityVO;
import com.giscloud.redis.utils.RedisUtils;
import com.giscloud.generator.utils.InterceptorUtils;
import com.giscloud.generator.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    public static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Value("${cookie.login.user}")
    private String cookieLoginUser;

    @Value("${cookie.login.psw}")
    private String cookieLoginPassword;

    @Value("${cookie.domain}")
    private String cookieDomain;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /***** 是否跳过登录 ****/
        if (InterceptorUtils.isIgnoreAuthentication(handler)) {
            return Boolean.TRUE;
        }
        String method = request.getMethod();
        if(!"GET".equals(method)&&!"POST".equals(method)&&!"HEAD".equals(method))
        {
            log.error("The request with Method["+method+"] was forbidden by server!");
            response.setContentType("text/html;charset=GBK");
            response.setCharacterEncoding("GBK");
            response.setStatus(403);
            response.getWriter().print("<font size=6 color=red>对不起，您的请求非法，系统拒绝响应!</font>");
            return false;
        }
        Boolean result = Boolean.FALSE;
        Integer state = -1;
        String message = "会话信息为空或已过期.";
        // 去request请求地址
        StringBuffer url = request.getRequestURL();
        log.debug("拦截器拦截请求地址为=======" + url);
        // cookie 解密
        String cookieValue = InterceptorUtils.decodeCookie(request,cookieLoginUser,cookieLoginPassword);
        log.debug("cookieValue====" + cookieValue);
        // 解密成功
        if (StringUtils.isNotEmpty(cookieValue)) {
            UserIdentityVO loginUserVo = FastJsonUtils.toBean(cookieValue, UserIdentityVO.class);
            String uuid = (String) redisUtils.get(RedisConstant.REDIS_SSO_ACCOUNT+String.valueOf(loginUserVo.getId()));//重复登录判断
            if (loginUserVo.getUuid() == null || uuid == null) {
                result = Boolean.FALSE;
                state = -11;
                message = "会话信息为空或已过期.";
            } else if (loginUserVo.getUuid().equals(uuid)) {
                String remoteIp = NetUtils.getRemoteIp(request);
                if (loginUserVo.getLoginIp().equals(remoteIp)) {
                    //COOKIE中用户登录IP与当前请求IP一致， 验证通过
                    request.setAttribute("staffName",loginUserVo.getRealName());
                    request.setAttribute("userVO", loginUserVo);
                    state = 0;
                    result = Boolean.TRUE;
                } else {
                    //COOKIE中用户登录IP与当前请求IP不一致， 验证失败
                    state = -13;
                    message = "您的网络环境已经改变，为了保障安全，请您重新登陆！";
                    result = Boolean.FALSE;
                }
            } else {
                state = -14;
                message = "您的账号已在其他地方登录，若不是本人操作，请修改密码！";
                result = Boolean.FALSE;
            }
        }
        if (!result) {
            // 判断ajax 请求
            if (InterceptorUtils.isAjaxRequest(request)) {
                response.setContentType("application/json; charset=utf-8");
                response.setCharacterEncoding("UTF-8");
                if(state == -1){
                    //未登录
                    response.setStatus(401);
                } else if(state == -11){
                    response.setStatus(402);
                } else if(state == -13){
                    response.setStatus(402);
                }else if(state == -14){
                    response.setStatus(402);
                }else {
                    response.setStatus(200);
                }
                PrintWriter pWriter = null;
                try {
                    pWriter = response.getWriter();
                    pWriter.write(FastJsonUtils.toJSONString(R.error(message)));
                } catch (IOException e) {
                    log.error("异常信息",e);
                } finally {
                    if (pWriter != null) {
                        pWriter.flush();
                        pWriter.close();
                    }
                }
            } else {
                request.setAttribute("state", state);
                request.setAttribute("message", message);
                request.getRequestDispatcher("/toLogin").forward(request, response);
                return false;
            }
        }
        return result;
    }

}
